<script setup lang="ts">
import { ca } from 'date-fns/locale'

const { user, loggedIn, fetch: fetchSession, clear } = useUserSession()
const toast = useToast()

// 左侧菜单：basic / account
type MenuKey = 'basic' | 'account'
const current = ref<MenuKey>('basic')

// 表单状态
const form = reactive({
  email: '',
  nickname: ''
})
const saving = ref(false)
const isModify = ref(false)

onMounted(async () => {
  await fetchSession()
  if (user.value) {
    form.email = (user.value as any).email || ''
    form.nickname = (user.value as any).nickname || (user.value as any).name || (user.value as any).username || ''
  }
})

watch(user, (val) => {
  if (val) {
    form.email = (val as any).email || ''
    form.nickname = (val as any).nickname || (val as any).name || (val as any).username || ''
  }
}, { immediate: false })

// 保存昵称
async function saveBasic() {
  if (!form.nickname) {
    toast.add({ title: '请输入昵称', color: 'warning', icon: 'i-lucide-alert-triangle' })
    return
  }
  saving.value = true
  try {
    // 约定：后端实现该接口以更新昵称
    await $fetch('/api/modify-nickname', {
      method: 'POST',
      body: { nickname: form.nickname }
    })
    await fetchSession()
    toast.add({ title: '保存成功', color: 'success', icon: 'i-lucide-check-circle' })
    isModify.value = false
  } catch (err: any) {
    toast.add({ title: '保存失败', description: err?.data?.statusMessage || '请稍后再试', color: 'error', icon: 'i-lucide-x-circle' })
  } finally {
    saving.value = false
  }
}

// 开始修改
function startEdit() {
  form.nickname = nickname.value || ''
  isModify.value = true
}

// 取消修改
function cancelEdit() {
  form.nickname = nickname.value || ''
  isModify.value = false
}

// 账户信息（示例数据，实际由服务端返回）
const membershipLevel = computed(() => (user.value as any)?.level || 'Free')
const membershipExpireAt = computed(() => (user.value as any)?.expireAt || null)

const displayName = computed(() =>
  (user.value as any)?.nickname || (user.value as any)?.email
)

// const email = user.value[0].email
// const nickname = user.value[0].nickname

const email = computed(() => user.value?.email || '')
const nickname = computed(() => user.value?.nickname || '')

async function onLogout() {
  await clear()
  await navigateTo('/')
}

useHead({ title: `用户中心 - ${displayName.value}` })
</script>

<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900">
    <div class="max-w-5xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
      <!-- 顶部 -->
      <div class="flex items-center justify-between mb-6">
        <NuxtLink to="/" class="inline-flex items-center gap-2 text-primary hover:text-primary-600 transition-colors">
          <UIcon name="i-lucide-arrow-left" class="w-5 h-5" />
          <span>返回首页</span>
        </NuxtLink>

        <div class="flex items-center gap-3">
          <span v-if="loggedIn" class="text-sm text-gray-600 dark:text-gray-300">{{ displayName }}</span>
          <UButton
            icon="i-lucide-log-out"
            color="neutral"
            variant="ghost"
            @click="onLogout"
          >退出</UButton>
        </div>
      </div>

      <div class="grid grid-cols-12 gap-6">
        <!-- 左侧菜单 -->
        <aside class="col-span-12 sm:col-span-3">
          <nav class="bg-white dark:bg-gray-800 rounded-md shadow divide-y divide-gray-100 dark:divide-gray-700">
            <button
              type="button"
              :class="[
                'w-full text-left px-4 py-3 text-sm rounded-t-md',
                current === 'basic' ? 'bg-primary/10 text-primary' : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              ]"
              @click="current = 'basic'"
            >
              基本信息
            </button>
            <button
              type="button"
              :class="[
                'w-full text-left px-4 py-3 text-sm rounded-b-md',
                current === 'account' ? 'bg-primary/10 text-primary' : 'text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              ]"
              @click="current = 'account'"
            >
              账户信息
            </button>
          </nav>
        </aside>

        <!-- 右侧内容 -->
        <section class="col-span-12 sm:col-span-9">
          <div class="bg-white dark:bg-gray-800 p-6 rounded-md shadow space-y-6">
            <!-- 基本信息 -->
            <div v-if="current === 'basic'" class="space-y-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">邮箱</label>
                <!-- <input
                  type="email"
                  :value="form.email"
                  disabled
                  class="mt-1 w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-200 cursor-not-allowed"
                /> -->
                {{ email }}
              </div>

              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">昵称</label>
                <div v-if="!isModify" class="flex ">
                  <input
                    :value="nickname"
                    type="text"
                    disabled
                    class="mt-1 w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  />
                  <UButton class="ml-10 mt-1 w-30 px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                    :label="'修改'"
                    block
                    :ui="{
                      // 展开时图标 + 文字间距微调
                      leadingIcon: 'text-muted',
                    }"
                    @click="startEdit"
                  />
                </div>
                <div v-else class="flex">
                  <input
                    v-model="form.nickname"
                    type="text"
                    placeholder="请输入昵称"
                    class="mt-1 w-full px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                  />
                  <UButton class="ml-10 mt-1 w-30 px-3 py-2 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100"
                    :label="'取消修改'"
                    block
                    :ui="{
                      // 展开时图标 + 文字间距微调
                      leadingIcon: 'text-muted',
                    }"
                    @click="cancelEdit"
                  />
                </div>
              </div>

              <div class="flex items-center gap-3">
                <UButton :loading="saving" color="primary" @click="saveBasic">保存</UButton>
                <NuxtLink to="/reset" class="text-sm text-primary hover:text-primary-600 underline">重置密码</NuxtLink>
              </div>
            </div>
            <!-- 账户信息 -->
            <div v-else class="space-y-4">
              <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600 dark:text-gray-300">当前账户级别</div>
                <div class="text-base font-medium text-highlighted">{{ membershipLevel }}</div>
              </div>
              <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600 dark:text-gray-300">会员到期时间</div>
                <div class="text-base font-medium text-highlighted">
                  {{ membershipExpireAt ? membershipExpireAt : '—' }}
                </div>
              </div>
              <div class="pt-2">
                <NuxtLink to="/pricing" class="text-sm text-primary hover:text-primary-600 underline">充值 / 购买会员</NuxtLink>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  </div>
</template>


